// import formData from "./metadata/formData-1.json" with {type: "json"};
import * as path from "node:path";
import * as fs from "node:fs";

/**
 * 登录
 */
async function login() {
    return '29aef7263c0742f3b488863a58fd0256';
}

/**
 * 获取采集表单数据
 */
async function getFormData() {
    const metadataDir = path.join(process.cwd(), 'metadata');
    const formDataList = [];

    async function getFileData(file) {
        return new Promise((resolve, reject) => {
            const filePath = path.join(metadataDir, file);
            fs.readFile(filePath, 'utf8', (err, data) => {
                if (err) {
                    console.error(`读取文件 ${file} 失败:`, err);
                    return;
                }
                try {
                    const formData = JSON.parse(data);
                    // 获取当前时间
                    const currentDate = new Date();
                    // 将当前时间转换为 ISO 8601 格式
                    const currentIsoDate = currentDate.toISOString();
                    // 替换 submittedAt 的值
                    formData.submittedAt = currentIsoDate;
                    resolve({fileName: file, formData: formData});
                } catch (parseError) {
                    console.error('解析JSON失败:', parseError);
                    reject(parseError);
                }
            });
        })
    }

    return new Promise((resolve, reject) => {
        // 列出目录中的所有文件
        fs.readdir(metadataDir, async (err, files) => {
            if (err) {
                console.error('读取目录失败:', err);
                return;
            }
            // 筛选出符合命名规则的文件
            const jsonFiles = files.filter(file => /\.json$/.test(file));
            if (jsonFiles.length === 0) {
                console.log('目录中没有符合条件的文件', metadataDir, files.length);
                return;
            }
            // 遍历读取所有文件
            for (const file of jsonFiles) {
                const formData = await getFileData(file);
                formDataList.push(formData);
            }
            resolve(formDataList);
        });
    });
}

/**
 * 获取代理人ID
 * {
 *     "code": 0,
 *     "data": {
 *         "id": 8,
 *         "userId": 5227,
 *         "agentGroupId": 1,
 *         "name": null,
 *         "tel": "17198640929",
 *         "gender": null,
 *         "status": 1,
 *         "remarks": null
 *     },
 *     "msg": ""
 * }
 */
async function getAgentId() {
    const response = await fetch(`https://api.mingyu.life/app-api/rights/agent/10000/login`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${await login()}`,
        },
    })
    const json = await response.json();
    if (json.code !== 0 || !json.data) {
        console.error('获取数据代理人失败', json);
        return null;
    }
    console.info('获取数据代理人成功', json.data);
    return json.data.id;
}

/**
 * 创建采集表单
 * {
 *     "code": 0,
 *     "data": {
 *         "id": 126,
 *         "agentId": 8,
 *         "reportFormData": null,
 *         "status": 0,
 *         "remarks": null
 *     },
 *     "msg": ""
 * }
 */
async function createReport() {
    const agentId = await getAgentId();
    if (!agentId) {
        return null;
    }
    const response = await fetch(`https://api.mingyu.life/app-api/rights/agent/${agentId}/report/create`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${await login()}`,
        },
    })
    const json = await response.json();
    if (json.code !== 0 || !json.data) {
        console.error('创建采集表单失败', json);
        return null;
    }
    console.info('创建采集表单成功', json.data);
    return [json.data.id, agentId];
}

/**
 * 获取已经存在的采集表单
 * {
 *     "code": 0,
 *     "data": {
 *         "id": 136,
 *         "agentId": 8,
 *         "reportFormData": null,
 *         "status": 0,
 *         "remarks": null
 *     },
 *     "msg": ""
 * }
 */
async function getReport() {
    const agentId = await getAgentId();
    if (!agentId) {
        return null;
    }
    const response = await fetch(`https://api.mingyu.life/app-api/rights/agent/${agentId}/report`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${await login()}`,
        },
    })
    const json = await response.json();
    if (json.code !== 0 || !json.data) {
        console.error('获取已经存在的采集表单失败', json);
        return null;
    }
    console.info('获取已经存在的采集表单成功', json.data);
    return [json.data.id, agentId];
}

/**
 * 提交数据
 * {"code":0,"data":true,"msg":""}
 * { code: 202302073, data: null, msg: '这份报告不属于您!' }
 */
async function updateReport(formData) {
    let report = null;
    const cr = await createReport();
    if (cr) {
        report = cr;
    } else {
        report = await getReport();
    }
    if (!report) {
        return false;
    }
    const [reportId, agentId] = report;
    if (!reportId || !agentId) {
        return false;
    }

    const formDataString = JSON.stringify(formData);
    // console.info('原始数据', formDataString);

    const formDataEncode = encodeURIComponent(formDataString);
    // console.info('编码数据', formDataEncode);

    const formDataBase64 = btoa(formDataEncode);
    // console.info('加密数据', formDataBase64);

    const request = {
        reportId: reportId,
        formData: formDataBase64,
    }
    // console.info('提交数据', '\n', JSON.stringify(request, null, 2));

    const response = await fetch(`https://api.mingyu.life/app-api/rights/agent/${agentId}/report/${reportId}/update`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${await login()}`,
        },
        body: JSON.stringify(request),
    })
    const json = await response.json();
    if (json.code !== 0 || json.data !== true) {
        console.error('提交失败', json);
        return false;
    }
    console.info('提交成功', json);
    return true;
}

/**
 * 带日志输出
 */
async function withLogger(count = 1, data) {
    console.log(' ');
    console.info(`第 ${count} 份表单`, `${data.fileName}`, new Date().toLocaleString(), '开始执行');
    const result = await updateReport(data.formData);
    if (result) {
        console.info(`第 ${count} 份表单`, `${data.fileName}`, new Date().toLocaleString(), '执行完成', '成功');
    } else {
        console.info(`第 ${count} 份表单`, `${data.fileName}`, new Date().toLocaleString(), '执行完成', '失败');
    }
    console.log(' ');
    return result;
}


setImmediate(async () => {
    const formDataList = await getFormData();
    for (let i = 0; i < formDataList.length; i++) {
        const result = await withLogger(i + 1, formDataList[i]);
        if (!result) {
            break;  // 终止
        }
        await new Promise(resolve => setTimeout(resolve, 1000));    // 间隔1秒
    }
})